﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Service.Model.Context;
using ShortBus;

namespace Service.Workflow.GamePlayer.Command
{
    public class CreateGamePlayerCommandHandler : IAsyncQueryHandler<CreateGamePlayerCommand, CreateGamePlayerCommandResponse>
    {
        private readonly ServiceDbContext dbContext;

        public CreateGamePlayerCommandHandler(ServiceDbContext serviceDbContext)
        {
            this.dbContext = serviceDbContext;
        }

        public async Task<CreateGamePlayerCommandResponse> HandleAsync(CreateGamePlayerCommand command)
        {
            var player = dbContext.Players.FirstOrDefault(p => p.PlayerId == command.PlayerId);
            var game = dbContext.Games.FirstOrDefault(g => g.GameId == command.GameId);

            if (player == null || game == null)
            {
                throw  new Exception("Error reading player or game");
            }

            var gamePlayer = new Model.GamePlayer()
            {
                Game = game,
                Player = player
            };

            dbContext.GamePlayers.Add(gamePlayer);

            await dbContext.SaveChangesAsync();

            return new CreateGamePlayerCommandResponse() {};
        }
    }
}